<?php
// +----------------------------------------------------------------------
// | 云静Admin
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2022 http://www.iyunj.cn
// +----------------------------------------------------------------------
// | 云静Admin提供个人非商业用途免费使用。
// +----------------------------------------------------------------------
// | Author: Uncle-L <1071446619@qq.com>
// +----------------------------------------------------------------------
// | 注意：
// | 1、配置 'url_common_param'=>true
// +----------------------------------------------------------------------
// | 初始化（禁止更改代码顺序）
// +----------------------------------------------------------------------

namespace yunj\core;

use think\facade\Event;
use think\facade\Middleware;
use think\facade\Route;
use yunj\app\admin\service\route\RouteFileService;
use yunj\app\admin\service\route\RouteService;
use yunj\app\admin\service\route\RouteSyncSystemDataService;

class Init {

    public function handle() {
        if (env('APP_DEBUG', false)) {
            ini_set("display_errors", "On");//打开错误提示
            ini_set("error_reporting", E_ALL);//显示所有错误
        }
        $this->init();
        $this->cors();
        $this->sysInit();
    }

    // 初始化
    private function init() {
        // 检测PHP环境
        if (version_compare(PHP_VERSION, '7.2.5', '<')) die('PHP版本过低，最少需要PHP7.2.5，请升级PHP版本！');

        // 短路径
        if (!defined('YUNJ_VENDOR_SHORT_PATH')) define('YUNJ_VENDOR_SHORT_PATH', ds_replace("vendor/yunj/admincore-tp6/"));
        // 根目录路径
        if (!defined('YUNJ_VENDOR_PATH')) define('YUNJ_VENDOR_PATH', root_path() . YUNJ_VENDOR_SHORT_PATH);
        // src路径
        if (!defined('YUNJ_VENDOR_SRC_PATH')) define('YUNJ_VENDOR_SRC_PATH', YUNJ_VENDOR_PATH . "src" . DIRECTORY_SEPARATOR);
        // 版本号
        if (!defined('YUNJ_VERSION')) define('YUNJ_VERSION', include YUNJ_VENDOR_SRC_PATH . "version.php");
        // path
        if (!defined('YUNJ_PATH')) define('YUNJ_PATH', root_path() . "yunj" . DIRECTORY_SEPARATOR);

        // 判断是否执行过安装操作
        if (!app()->runningInConsole() && !is_initialized()) {
            die('请执行初始化系统命令：php think yunj:init');
        }
        // 后台系统入口
        if (!defined('YUNJ_ADMIN_ENTRANCE')) {
            $entrance = yunj_config('admin.entrance');
            if (is_null($entrance) || !$entrance) $entrance = 'admin';
            if (!is_string($entrance)) die('yunj\config\admin.php 内配置 entrance 需为字符串格式');
            $entrance = trim($entrance);
            if (substr($entrance, 0, 1) == '/') $entrance = substr(1);
            if (!$entrance) $entrance = 'admin';
            define('YUNJ_ADMIN_ENTRANCE', $entrance);
        }

        // 引入文件
        $this->includeFiles();

        // 初始化路由
        $this->initRoute();
    }

    // 初始化路由
    private function initRoute() {
        // 路由文件
        $routePath = ds_replace(YUNJ_PATH . 'temp/route/route.php');
        if (!file_exists($routePath)) {
            if (app()->runningInConsole()) {
                return;
            }
            if (is_initialized()) {
                // 重新执行路由文件初始化
                RouteFileService::reset();
                if (!file_exists($routePath)) {
                    die('云静路由文件缺失，请执行初始化系统路由命令：php think yunj:route');
                }
            } else {
                die('请执行初始化系统命令：php think yunj:init');
            }
        }
        include_once $routePath;
        // 首页地址
        if (!defined('YUNJ_ADMIN_URL')) define('YUNJ_ADMIN_URL', build_url('yunjAdminIndex'));
    }

    // 引入文件
    private function includeFiles(): void {
        // 引入app下init文件
        $appDirPath = YUNJ_VENDOR_SRC_PATH . 'app';
        $appDirFileArr = scandir($appDirPath);
        foreach ($appDirFileArr as $file) {
            if ($file === "." || $file === "..") continue;
            $initFilePath = $appDirPath . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . 'init.php';
            if (file_exists($initFilePath)) {
                include_once $initFilePath;
            }
        }
    }

    // CORS跨域请求处理
    private function cors() {
        $enable = yunj_config('cors.enable', false);
        if (!$enable) return;
        $origin = yunj_config('cors.access_control_allow_origin', '*');
        $origin = $origin ?: '*';
        $methods = yunj_config('cors.access_control_allow_methods', '');
        $methods = $methods && (substr($methods, 0, 1) !== ',') ? ',' . $methods : $methods;
        $headers = yunj_config('cors.access_control_allow_headers', '');
        $headers = $headers && (substr($headers, 0, 1) !== ',') ? ',' . $headers : $headers;
        header('Access-Control-Allow-Origin:' . $origin);
        header('Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS' . $methods);
        header("Access-Control-Allow-Headers:token,Origin,X-Requested-With,Content-Type,Accept" . $headers);
        if (request()->isOptions()) exit();
    }

    // 系统初始化
    private function sysInit() {
        $this->eventListen();
        // 中间件注册
        Middleware::unshift(\yunj\app\admin\middleware\Init::class);
    }

    // 事件监听
    private function eventListen() {
        Event::listen('HttpRun', 'yunj\core\listener\HttpRun');
    }

}